<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模拟数据生成器</title>
    <link rel="stylesheet" href="elementUI/css/index.css">
</head>
<body>
<div id="app">
    <el-row>
        <el-col :span="12"><div class="grid-content bg-purple">
                <el-form ref="form" :model="form" label-width="80px">
                    <el-form-item label="活动名称">
                        <el-input
                                type="textarea"
                                :rows="20"
                                placeholder="请输入内容"
                                v-model="form.jsonStr">
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="simulationData">立即生成</el-button>
                    </el-form-item>
                </el-form>
            </div></el-col>
        <el-col :span="12"><div class="grid-content bg-purple-light">
                <el-form ref="form" :model="form" label-width="80px">
                    <el-form-item label="结果">
                        <el-input
                                type="textarea"
                                :rows="20"
                                placeholder="请输入内容"
                                v-model="form.resultStr">
                        </el-input>
                    </el-form-item>
                </el-form>
            </div></el-col>
    </el-row>
</div>

<script type="text/javascript" src="js/vue.min.js"></script>
<script type="text/javascript" src="elementUI/index.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>

<script>
    var vm = new Vue({
        el: '#app',
        data () {
            return {
                form: {
                    jsonStr2: {
                        outputType: "sql",    // 输出类型
                        frequency: 50,  // 次数
                        tableName: "test", // 输出sql语句的表名
                        data: { // 数据, K:字段名称， V：值或内置函数, 需加""
                            /**
                             * id生成器：
                             * len：长度
                             */
                            id: "@getId?len=18", // ：len：数据长度
                            /**
                             * 随机字符串生成器：
                             * type：类型，1：数字，2：小写字母，3：大写字母，4：特殊字符
                             * len：长度
                             */
                            name: "@randomStr?type=1234&len=24",
                            /**
                             * 随机取数组元素：
                             */
                            type: "[1,2,3,4]",
                            /**
                             * 固定值：
                             */
                            age: "15"
                        },
                        /**
                         * 定义字段类型：
                         * string | int
                         */
                        type:{
                            id: "int",
                            name: "string",
                            type: "int",
                            age: "int"
                        }
                    },
                    jsonStr: '{\n' +
                        '   "outputType": "sql",\n' +
                        '   "frequency": 50,\n' +
                        '   "tableName": "test",\n' +
                        '   "data": {\n' +
                        '   	"id": "@getId?len=18",\n' +
                        '   	"name": "@randomStr?type=1234&len=24",\n' +
                        '   	"type": [1, 2, 3, 4],\n' +
                        '   	"age": "15"\n' +
                        '   },\n' +
                        '   "type": {\n' +
                        '   	"id": "int",\n' +
                        '   	"name": "string",\n' +
                        '   	"type": "int",\n' +
                        '   	"age": "int"\n' +
                        '   }\n' +
                        '}',
                    resultStr: ''
                }
            }
        },
        methods: {
            javaScriptCode(){
                JSON.stringify(this.jsonStr, null, 4)
            },
            // 生成数据
            simulationData () {
                // 将json字符串转换为对象
                var jsonData = JSON.parse(this.form.jsonStr)
                // 输出结果
                var data = []
                console.log(parseInt(jsonData.frequency))
                for (var i = 0; i < parseInt(jsonData.frequency); i++) {
                    var singleStripData = {}
                    for (let key in jsonData.data) {
                        var v = jsonData.data[key]
                        // 判断v是数组还是字符串
                        if (typeof (v) === 'string') { // 字符串
                            singleStripData[key] = this.judgeValue(v)
                        } else {
                            // 判断是否数组
                            if (v instanceof Array) {
                                singleStripData[key] = v[vm.randomNum(0, v.length - 1)]
                            }
                        }
                    }
                    data.push(singleStripData)
                }
                var sqlStr = ""
                for (var i = 0; i < data.length; i++) {
                    var fieldStr = ""
                    var dataStr = ""
                    for (let key in data[i]) {
                        if (fieldStr != ""){
                            fieldStr += ","
                        }
                        fieldStr += "`" + key + "`"
                        if (dataStr != ""){
                            dataStr += ","
                        }
                        // 写入数据
                        switch (jsonData.type[key]) {
                            case "string":
                                dataStr += "'" + data[i][key] + "'"
                                break
                            case "int":
                                dataStr += parseInt(data[i][key])
                                break
                        }
                    }
                    sqlStr += "INSERT INTO " + "`" + jsonData.tableName + "`" + "(" + fieldStr + ") VALUES (" + dataStr + ");\n"
                }
                this.form.resultStr = sqlStr
                // 获取data
                console.log(jsonData)
                console.log(data)
            },
            // 判断内容返回值
            judgeValue (v) {
                if (v.indexOf('@getId') != -1) {    // 生成id
                    return this.getId(v)
                } else if (v.indexOf('@randomStr') != -1) { // 获取随机字符
                    return this.randomString(v)
                }else if (v.indexOf('@randomDate') != -1) { // 获取随机时间
                    return this.randomDate(v)
                }else if (v.indexOf('@randomNum') != -1) { // 获取随机数
                    return this.randomNum2(v)
                } else {
                    return v
                }
            },
            // 随机数
            randomNum2(funcStr){
                var max = this.getQueryVariable(funcStr, "max") // 开始时间
                var min = this.getQueryVariable(funcStr, "min")   // 结束时间
                // 将时间戳转换为时间字符串
                return this.randomNum (parseInt(min), parseInt(max))
            },
            // 随机时间
            randomDate(funcStr){
                var startTime = this.getQueryVariable(funcStr, "startTime") // 开始时间
                var endTime = this.getQueryVariable(funcStr, "endTime")   // 结束时间
                var format = this.getQueryVariable(funcStr, "format")   // 日期格式
                // 将时间范围转换为时间戳
                var startTimestamp = Date.parse(startTime)
                var endTimestamp = Date.parse(endTime)
                // 获取范围内的随机时间
               var timeTimestamp = this.randomNum (startTimestamp, endTimestamp)
                // 将时间戳转换为时间字符串
                console.log(this.getdate())
                // return this.formatTime(timeTimestamp, format)
                return ""
            },
            // 获取日期
            getdate(){
                var arr=new Array();
                var startTime = new Date('2018','01','01').getTime();
                var endTime = new Date('2018','01','31').getTime();
                for( var i = startTime ; i <= endTime ; ){
                    arr.push(this.formatTime(i,'-'));
                    i += 24 * 60 * 60 * 1000;
                }
                return arr;
            },
            // 日期格式化
            formatTime(time,spliter){
                var d = new Date(time);
                var year = d.getFullYear();
                var month = d.getMonth() >= 10 ? d.getMonth() : ('0' + d.getMonth());
                var day = d.getDate() >= 10 ? d.getDate() : ('0' + d.getDate());
                return year+spliter+month+spliter+day;
            },
            // 随机字符串
            randomString(funcStr) {
                var str = 'abcdefghijklmnopqrstuvwxyz9876543210';
                var len = this.getQueryVariable(funcStr, "len")
                var type = this.getQueryVariable(funcStr, "type")
                if (type.indexOf('1') != -1) {    // 数字
                    str += "9876543210"
                }
                if (type.indexOf('2') != -1) {    // 小写字母
                    str += "abcdefghijklmnopqrstuvwxyz"
                }
                if (type.indexOf('3') != -1) {    // 大写字母
                    str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                }
                if (type.indexOf('4') != -1) {    // 特殊字符
                    str += "!@#$%^&*()_+-=[]{}|;:'\"\\<>,./?"
                }

                let tmp = '',
                    i = 0,
                    l = str.length;
                for (i = 0; i < len; i++) {
                    tmp += str.charAt(Math.floor(Math.random() * l));
                }
                return tmp;
            },
            // id生成
            getId (funcStr) {
                // 获取参数
                var len = this.getQueryVariable(funcStr, "len")
                var id = this.GenNonDuplicateID(len)
                return id
            },
            GenNonDuplicateID(randomLength){
                var a = Math.random()
                var b = a.toString().substr(3,12)
                var c = Date.now()
                var d = b + c
                // var e = d.toString().substr(3,randomLength)
                var f = d.toString(36)
                var e = f.substr(3,randomLength)

                return e
            },
            /**
             * 解析参数
             * @param funcStr 函数名与参数 例：@getId?type=2&len=18
             * @param name 参数名
             * @return {string} 参数值
             */
            getQueryVariable (funcStr, name) {
                var reg = new RegExp('(^|\\?|&)' + name + '=([^&]*)(\\s|&|$)', 'i')
                if (reg.test(funcStr)) {
                    return decodeURIComponent(RegExp.$2.replace(/\+/g, ' '))
                }
                return ''
            },
            randomNum (Min, Max) {
                var Range = Max - Min
                var Rand = Math.random()
                return (Min + Math.round(Rand * Range))
            }
        },
        mounted () {

        }
    })
</script>
</body>
